 package com.zy.multiredis.config;

import java.util.Map;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.boot.context.properties.bind.Bindable;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import com.zy.multiredis.util.MultiRedisInfoHolder;

@Component
public class MultiRedisBeanDefinitionRegistryPostProcessors implements BeanDefinitionRegistryPostProcessor,EnvironmentAware{

    private Environment environment;
    
    private static final String multi_REDIS_PROPERTY = "redis.multi";
    
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    }

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        Map<String, RedisProperties> multiRedisInfos =
            Binder.get(environment).bind(multi_REDIS_PROPERTY, Bindable.mapOf(String.class, RedisProperties.class)).get();
        MultiRedisInfoHolder.setmultiRedisInfos(multiRedisInfos);
        for (String beanName : multiRedisInfos.keySet()) {
            if(!registry.containsBeanDefinition(beanName)) {
                BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(RedisTemplate.class);
                BeanDefinition beanDefinition = beanDefinitionBuilder.getRawBeanDefinition();
                beanDefinition.setAttribute("auto", true);
                registry.registerBeanDefinition(beanName, beanDefinition);
            }
        }
    }

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }
}
